#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/3 1:01
# @Author : 闫峰
# @File    : sender.py
import pika
import json


class MQSender:
    def __init__(self, host, queue, username, password):
        credentials = pika.PlainCredentials(username, password)
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host, credentials=credentials))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=queue)
        self.queue = queue

    def send(self, message):
        # 将消息序列化为JSON格式
        json_message = json.dumps(message)
        # 发送消息
        self.channel.basic_publish(exchange='', routing_key=self.queue, body=json_message)

    def close(self):
        self.connection.close()
